package com.zhss.eshop.order.price.promotion.reach;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhss.eshop.commodity.domain.dto.CommodityGoodsSkuDTO;
import com.zhss.eshop.commodity.service.CommodityService;
import com.zhss.eshop.order.domain.dto.OrderItemDTO;
import com.zhss.eshop.order.price.promotion.AbstractGiftPromotionActivityCalculator;
import com.zhss.eshop.order.price.promotion.PromotionActivityCalculator;
import com.zhss.eshop.order.price.promotion.PromotionActivityResult;
import com.zhss.eshop.promotion.domain.dto.PromotionActivityDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 满赠类型的促销胡活动的处理器
 * @author suyuan
 *
 */
@Component
public class ReachGiftPromotionActivityCalculator
		extends AbstractGiftPromotionActivityCalculator
		implements PromotionActivityCalculator {

	/**
	 * 商品中心接口
	 */
	@Autowired
	private CommodityService commodityService;

//	@Autowired
//	private JsonExtractor jsonExtractor;

	/**
	 * 计算促销活动的减免金额
	 */
	@Override
	public PromotionActivityResult calculate(OrderItemDTO item,
											 PromotionActivityDTO promotionActivity) throws Exception {
		Double totalAmount = item.getPurchaseQuantity() * item.getPurchasePrice();

		JSONObject rule = JSONObject.parseObject(promotionActivity.getRule());
		Double thresholdAmount = rule.getDouble( "thresholdAmount");
		JSONArray giftGoodsSkuIds = rule.getJSONArray("giftGoodsSkuIds");

		if(totalAmount > thresholdAmount) {
			PromotionActivityResult result = new PromotionActivityResult();

			for(int i = 0; i < giftGoodsSkuIds.size(); i++) {
				Long goodsSkuId = giftGoodsSkuIds.getLong(i);
				CommodityGoodsSkuDTO goodsSku = commodityService.getGoodsSkuById(goodsSkuId);
				result.getOrderItems().add(createOrderItem(goodsSku));
			}

			return result;
		}

		return new PromotionActivityResult();
	}

}
